package spring_boot.corona.track.experiment3.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import spring_boot.corona.track.experiment3.models.RegionStats;
import spring_boot.corona.track.experiment3.services.GetDataService;

import java.util.List;

/**
 * @Author: 王志华
 * @Date: 2020/11/11
 */
@Controller
public class HomeController {

    // 通过构造函数实现注入
    GetDataService getDataService;

    public HomeController(GetDataService getDataService) {
        this.getDataService = getDataService;
    }

    // 使用Thymeleaf进行前端展示
    @RequestMapping("/javaweb/show")
    public String show(Model m, @ModelAttribute RegionStats regionStats) {

        List<RegionStats> datalist = getDataService.getAllRegionStats();    // 获取所有数据列表
        List<String> countrylist = getDataService.getDeduplicationCountry(datalist);    // 获取去重后的国家名列表

        // 分别获取全球和选定国家的确诊总数
        int globalSum = 0, countrySum = 0;
        for (int i = 0; i < datalist.size(); i++) {
            globalSum += datalist.get(i).getLatestTotalCases();
            if (datalist.get(i).getCountry().equals(regionStats.getCountry())) {
                countrySum += datalist.get(i).getLatestTotalCases();
            }
        }

        // 分别获取全球和选定国家的每月确诊数
        int[] globalDateNewAdd = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        int[] countryDateNewAdd = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        List<String> date = datalist.get(0).getDateList();
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < datalist.size(); j++) {
                for (int k = 0; k < date.size(); k++) {
                    String[] split = date.get(k).split("\\.");
                    if (split[1].equals(String.valueOf(i + 1))) {
                        globalDateNewAdd[i] += datalist.get(j).getDayAdd().get(date.get(k));
                        if (datalist.get(j).getCountry().equals(regionStats.getCountry())) {
                            countryDateNewAdd[i] += datalist.get(j).getDayAdd().get(date.get(k));
                        }
                    }
                }
            }
        }

        m.addAttribute("global_sum", globalSum);
        m.addAttribute("country_sum", countrySum);

        m.addAttribute("global_date_add", globalDateNewAdd);
        m.addAttribute("country_date_add", countryDateNewAdd);

        m.addAttribute("c", regionStats.getCountry() == null ? "All" : regionStats.getCountry());      // 用于输出选定的国家数据
        m.addAttribute("regionStatsFromSelect", new RegionStats());
        m.addAttribute("allData", datalist);
        m.addAttribute("allCountry", countrylist);
        return "show";
    }

}
